<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">商品管理</h1>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-input
            v-model="searchForm.keyword"
            clearable
            placeholder="搜索商品名称或描述"
            style="width: 250px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>

        <!-- 分类筛选 -->
        <CategorySelector
            v-model="searchForm.categoryId"
            include-all
            mode="group"
            placeholder="选择商品分类"
            width="200px"
            @change="handleSearch"
        />

        <el-select
            v-model="searchForm.status"
            clearable
            placeholder="商品状态"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="1" label="上架"/>
          <el-option :value="0" label="下架"/>
        </el-select>

        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>

        <el-button @click="handleReset">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </div>

      <div class="table-toolbar-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon>
            <Plus/>
          </el-icon>
          添加商品
        </el-button>

        <el-button @click="handleRefresh">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 商品表格 -->
    <div class="table-container">
      <el-table
          v-loading="loading"
          :data="products"
          stripe
          style="width: 100%"
      >
        <el-table-column label="ID" prop="id" width="80"/>

        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <img
                v-if="row.mainImage"
                :src="row.mainImage"
                alt="商品图片"
                class="product-image"
                @click="previewImage(row.mainImage)"
            />
            <el-icon v-else color="#ccc" size="40">
              <Picture/>
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column label="商品名称" min-width="200" prop="name"/>

        <el-table-column label="分类" prop="categoryName" width="120"/>

        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>

        <el-table-column label="库存" prop="stock" width="80">
          <template #default="{ row }">
            <el-tag :type="getStockTagType(row.stock)" size="small">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="销量" prop="sales" width="80"/>

        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="250">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(row)"
              >
                编辑
              </el-button>

              <el-button
                  size="small"
                  type="info"
                  @click="handleStockEdit(row)"
              >
                库存
              </el-button>

              <el-button
                  v-if="row.status === 1"
                  size="small"
                  type="warning"
                  @click="handleUpdateStatus(row, 0)"
              >
                下架
              </el-button>

              <el-button
                  v-else
                  size="small"
                  type="success"
                  @click="handleUpdateStatus(row, 1)"
              >
                上架
              </el-button>

              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="图片预览" width="500px">
      <div class="image-preview-container">
        <img :src="previewImageUrl" alt="预览图片" style="width: 100%; height: auto;"/>
      </div>
    </el-dialog>

    <!-- 库存编辑对话框 -->
    <StockEditDialog
        v-model="stockDialogVisible"
        :product="selectedProduct"
        @success="handleStockEditSuccess"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Picture, Plus, Refresh, Search} from '@element-plus/icons-vue'
import {useProductStore} from '@/store/product'
import {useCategoryStore} from '@/store/category'
import {formatDateTime} from '@/utils'
import CategorySelector from '@/components/CategorySelector.vue'
import StockEditDialog from './components/StockEditDialog.vue'

// 路由
const router = useRouter()

// Store
const productStore = useProductStore()
const categoryStore = useCategoryStore()

// 响应式数据
const searchForm = reactive({
  keyword: '',
  categoryId: null,
  status: null
})

const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
const stockDialogVisible = ref(false)
const selectedProduct = ref(null)

// 计算属性
const products = computed(() => productStore.products)
const loading = computed(() => productStore.loading)
const total = computed(() => productStore.total)
const currentPage = computed({
  get: () => productStore.currentPage,
  set: (value) => productStore.setPagination(value, productStore.pageSize)
})
const pageSize = computed({
  get: () => productStore.pageSize,
  set: (value) => productStore.setPagination(productStore.currentPage, value)
})


// 方法
const handleSearch = () => {
  productStore.setPagination(1, pageSize.value)
  loadProductList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    categoryId: null,
    status: null
  })
  handleSearch()
}

const handleRefresh = () => {
  loadProductList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadProductList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadProductList()
}

const handleCreate = () => {
  router.push('/products/create')
}

const handleEdit = (product) => {
  router.push(`/products/edit/${product.id}`)
}

const handleStockEdit = (product) => {
  selectedProduct.value = product
  stockDialogVisible.value = true
}

const handleUpdateStatus = async (product, status) => {
  try {
    const action = status === 1 ? '上架' : '下架'
    await ElMessageBox.confirm(
        `确定要${action}商品 "${product.name}" 吗？`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await productStore.updateProductStatus(product.id, status)
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新商品状态失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

const handleDelete = async (product) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除商品 "${product.name}" 吗？此操作不可恢复！`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
    )

    await productStore.deleteProduct(product.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const handleStockEditSuccess = () => {
  stockDialogVisible.value = false
  loadProductList()
}

const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  imagePreviewVisible.value = true
}

const getStockTagType = (stock) => {
  if (stock <= 0) return 'danger'
  if (stock <= 10) return 'warning'
  return 'success'
}

const loadProductList = async () => {
  try {
    await productStore.getProductList(searchForm)
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载失败，请重试')
  }
}

const loadCategoryOptions = async () => {
  try {
    // 加载平铺分类数据用于构建级联选择器
    await categoryStore.getCategoryList({
      current: 1,
      size: 1000,
      status: 1
    })
  } catch (error) {
    console.error('加载分类选项失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadProductList()
  loadCategoryOptions()
})
</script>

<style scoped>
.page-container {
  padding: var(--admin-space-lg);
  background: var(--admin-bg-layout);
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: var(--admin-space-lg);
  padding: var(--admin-space-lg);
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  color: var(--admin-text-primary);
  font-size: var(--admin-font-xl);
  font-weight: var(--admin-font-semibold);
  line-height: var(--admin-line-height-sm);
}

.table-container {
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  padding: var(--admin-space-lg);
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
}

.table-toolbar-left {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.table-toolbar-right {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: var(--admin-radius-md);
  cursor: pointer;
  border: 1px solid var(--admin-border-light);
  transition: all 0.3s ease;
}

.product-image:hover {
  border-color: var(--admin-primary);
  box-shadow: var(--admin-shadow-sm);
  transform: scale(1.05);
}

.price {
  color: var(--admin-warning);
  font-weight: 600;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 16px 20px;
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
}

.image-preview-container {
  text-align: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  overflow: hidden;
  box-shadow: var(--admin-shadow-sm);
}

:deep(.el-table th.el-table__cell) {
  background: var(--admin-bg-secondary);
  color: var(--admin-text-primary);
  font-weight: 600;
  border-bottom: 1px solid var(--admin-border-light);
}

:deep(.el-table .el-table__row:hover > td) {
  background: var(--admin-bg-secondary);
}

/* 状态标签样式 */
:deep(.el-tag) {
  border-radius: var(--admin-radius-sm);
  font-weight: 500;
}

/* 操作按钮样式 */
:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 搜索框样式 */
:deep(.el-input__wrapper) {
  border-radius: var(--admin-radius-md);
}

:deep(.el-select .el-input__wrapper) {
  cursor: pointer;
}
</style>
